<template>
  <div class="box">
    <el-header height="40px">
      <el-form :inline="true" :model="queryData" class="form">
        <el-form-item label="角色查询">
          <el-input v-model="queryData.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
    </el-header>
    <el-main align="center">
      <el-button type="primary" icon="el-icon-plus" @click="addRole">增加</el-button>
      <el-button type="danger" icon="el-icon-delete" @click="deleteBatch">删除</el-button>
      <el-button type="primary" icon="el-icon-files" @click="addResource">资源分配</el-button>
      <el-button type="primary" icon="el-icon-user" @click="assignUser">用户分配</el-button>
      <el-button type="primary" icon="el-icon-office-building" disabled>公司分配</el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="onSubmit">刷新</el-button>
      <el-table
        ref="roleTable"
        :data="tableData"
        :header-cell-style="{'text-align':'center'}"
        :cell-style="{'text-align':'center'}"
        height="450px"
        :row-key="getRowKeys"
        :border="true"
        style="width: 100%;margin-top: 20px;margin-bottom: 25px;"
        @row-dblclick="handleEdit"
        @selection-change="handleSelectionChange"
      >
        <el-table-column fixed type="selection" width="50" />
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="name" label="角色" width="126" />
        <el-table-column prop="code" label="角色代码" width="100" />
        <el-table-column prop="remark" label="角色备注" width="100" />
        <el-table-column prop="companyDTO.name" label="所属公司" width="80" />
        <el-table-column prop="organizationDTO.name" label="所属机构" width="80" />
        <el-table-column
          prop="status"
          label="标签"
          width="80"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status === 0 ? 'danger' : 'success'"
              disable-transitions
              size="mini"
            >{{ scope.row.status?"启用":"停用" }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="primary"
              @click="handleCopy(scope.$index, scope.row)"
            >复制</el-button>
            <el-button
              size="mini"
              type="default"
              @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button>
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
            <el-button
              size="mini"
              type="warning"
              @click="handleViewPermissions(scope.$index, scope.row)"
            >查看权限</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="paginationInfo.pageNum"
        :page-sizes="[10, 20, 30, 40,50]"
        :page-size="paginationInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationInfo.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
      <ResourceDialog ref="ResourceDialog" :roles-id="rolesID" :dialog-type="resourceDialogType" @endEvent="clearSelection" />
      <UserInfoDialog ref="UserInfoDialog" :role-i-d="roleID" :dialog-type="UserInfoDialogType" @EndEvent="getRoleList(queryData)" />
      <assignUserDialog ref="assignUserDialog" :roles-id="rolesID" @assignUserEnd="getRoleList(queryData)" />
    </el-main>
  </div>
</template>

<script>
import { getRoleListAPI, getRoleByNameAPI, DeleteRoleAPI, deleteRoleBatchAPI } from '@/api/rolesAPI'
import ResourceDialog from './components/ResourceDialog.vue'
import UserInfoDialog from './components/userInfoDialog'
import assignUserDialog from './components/assignUserDialog.vue'
export default {
  components: {
    ResourceDialog,
    UserInfoDialog,
    assignUserDialog
  },
  data() {
    return {
      defaultQueryData: {
        pageNum: 1,
        pageSize: 10
      },
      queryData: {
        pageNum: 1,
        pageSize: 10,
        name: ''
      },
      roleID: '',
      rolesID: [],
      tableData: [],
      paginationInfo: {},
      TreeData: [],
      multipleSelection: [],
      resourceDialogType: 'VIEW',
      UserInfoDialogType: 'EDIT'
    }
  },
  mounted() {
    this.inintUI()
    this.getRoleList(this.defaultQueryData)
  },
  methods: {
    getRowKeys(row) {
      return row.id // id 能标识唯一的 table 行;
    },
    handleSelectionChange(val) {
      // console.log(val)
      this.multipleSelection = []
      // 假设取出 id 字段
      val.forEach(item => {
        const newObject = {}
        newObject.id = item.id
        newObject.version = item.version
        // 判断数组中是否包含这个 id
        if (this.multipleSelection.indexOf(newObject.id) === -1) {
          this.multipleSelection.push(newObject)
        }
      })
      console.log(this.multipleSelection)
    },
    /**
     * 界面初始化
     */
    inintUI() {
      this.rolesID = []
      this.tableData = []
      this.queryData = this.defaultQueryData
    },
    /**
    *向后端发起请求，获取页面数据
    */
    getRoleList(queryData) {
      // 获取数据动作
      this.roleID = ''
      getRoleListAPI(queryData)
        .then(
          (compos) => {
            this.tableData = compos.data
            const { total, pageNum, pageSize, pages } = compos
            this.paginationInfo = { total, pageNum, pageSize, pages }
            this.paginationInfo.total = parseInt(this.paginationInfo.total)
          }
        ).catch((error) => {
          this.$message.error(error)
        })
    },
    /**
     * 操作中编辑按钮功能
     * @param {*} index
     * @param {*} row
     */
    handleEdit(index, row) {
      this.UserInfoDialogType = 'EDIT'
      this.roleID = row.id
      this.$nextTick(() => { this.$refs.UserInfoDialog.onShow() })
      console.log(index, row)
    },
    /**
       * 操作中删除功能实现
       * @param {*} index
       * @param {*} row
       */
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        DeleteRoleAPI(row.id, row.version)
          .then((res) => {
            if (res) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
            this.queryData.name = ''
            this.$refs.roleTable.toggleRowSelection(row, false)
            this.getRoleList(this.queryData)
          })
          .catch((error) => {
            this.$message.error(error)
          })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

      console.log(index, row)
    },
    /**
     *操作中复制功能实现
     * @param {*} index
     * @param {*} row
     */
    handleCopy(index, row) {
      this.UserInfoDialogType = 'COPY'
      this.roleID = row.id
      this.$nextTick(() => { this.$refs.UserInfoDialog.onShow() })

      console.log(index, row)
    },
    /**
     *操作中查看权限功能实现
     * @param {*} index
     * @param {*} row
     */
    handleViewPermissions(index, row) {
      this.resourceDialogType = 'VIEW'
      this.$nextTick(() => { this.$refs.ResourceDialog.onShow(row.id) })

      console.log(index, row)
    },
    /**
     * 查询按钮提交功能实现
     */
    onSubmit() {
      getRoleByNameAPI(this.queryData)
        .then(compos => {
          this.tableData = compos.data
          const { total, pageNum, pageSize, pages } = compos
          this.paginationInfo = { total, pageNum, pageSize, pages }
          this.paginationInfo.total = parseInt(this.paginationInfo.total)
        }).catch(erro => {
          this.$message.error(erro)
        })
      console.log('submit!')
    },
    /**
     * 页面条数修改处理
     * @param {*} val
     */
    handleSizeChange(val) {
      this.paginationInfo.pageSize = val
      /**
       * 根据新size重新发起请求
       */
      this.queryData = this.paginationInfo
      this.getRoleList(this.queryData)
      console.log(`每页 ${val} 条`)
    },
    /**
     * 页面跳转处理
     * @param {*} val
     */
    handleCurrentChange(val) {
      this.paginationInfo.pageNum = val
      /**
       * 根据新页码重新发起请求
       */
      console.log(`当前页: ${val}`)
      this.queryData = this.paginationInfo
      this.getRoleList(this.queryData)
    },
    /**
     * 资源分配按钮逻辑处理
     */
    addResource() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请至少选择一个角色')
      } else {
        this.rolesID = this.multipleSelection
        this.resourceDialogType = 'ADD'
        this.$nextTick(() => {
          this.$refs.ResourceDialog.onShow()
        })
      }
    },
    /**
     * 批量删除
     */
    deleteBatch() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请至少选择一个角色')
      } else {
        this.$confirm('此操作将删除选中角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteRoleBatchAPI(this.multipleSelection)
            .then((res) => {
              if (res) {
                this.$message({
                  type: 'success',
                  message: '删除成功!'
                })
              }
              this.$refs.roleTable.clearSelection()
              this.queryData.name = ''
              this.getRoleList(this.QueryData)
            })
            .catch(error => {
              this.$message.error(error)
            })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    /**
     * 添加角色按钮逻辑处理
     */
    addRole() {
      this.UserInfoDialogType = 'ADD'
      this.$nextTick(() => {
        this.$refs.UserInfoDialog.onShow()
      })
    },
    /**
     * 分配用户按钮逻辑处理
     */
    assignUser() {
      if (this.multipleSelection.length === 0) {
        this.$message.error('请至少选择一个角色')
      } else {
        this.rolesID = this.multipleSelection
        this.$nextTick(() => {
          this.$refs.assignUserDialog.onShow()
        })
      }
    },
    clearSelection() {
      this.$refs.roleTable.clearSelection()
    }
  }
}
</script>
<style scoped>
.box{
  background-color:  #FFFFFF;
  /* position: relative; */
  box-shadow: 0px -5px 24px 0px #92979c;
  width:1100px;
  padding-top:30px;
}
</style>
